package cn.itcast.core.util;

import java.util.ArrayList;
import java.util.List;

public class QueryHelper {
	
	private List<Object> parameters;
	//from 子句
	private String fromClause = "";
	//where 子句
	private String whereClause = "";
	//order by 子句
	private String orderByClause = "";
	//排序序列 升序
	public static String ORDER_BY_ASC = "ASC";
	//排序序列 降序
	public static String ORDER_BY_DESC = "DESC";
	
	//构造from 子句
	public QueryHelper(Class clazz, String alias){
		fromClause = "FROM " + clazz.getSimpleName() + " " + alias;
	}
	
	/**
	 * 构造where 子句
	 * @param condition 查询条件；如：i.title like ?
	 * @param params 查询条件值；如： %标题%
	 */
	public void addCondition(String condition, Object... params){
		if(whereClause.length() > 0){//非第一个查询条件
			whereClause += " AND " + condition;
		} else {//第一个查询条件
			whereClause = " WHERE " + condition;
		}
		
		if(parameters == null){
			parameters = new ArrayList<Object>();
		}
		
		//条件查询条件值
		if(params != null){
			for(Object param: params){
				parameters.add(param);
			}
		}
	}
	
	/**
	 * 构造order by子句
	 * @param property 排序属性；如：i.createTime
	 * @param order 排序序列，如：DESC(降序) 或者 ASC(升序)
	 */
	public void addOrderByProperty(String property, String order){
		if(orderByClause.length() > 0){//非第一个排序属性
			orderByClause += "," + property + " " + order;
		} else {//第一个排序属性
			orderByClause = " ORDER BY " + property + " " + order;
		}
	}
	
	//获取查询列表的hql
	public String getQueryListHql(){
		return fromClause + whereClause + orderByClause;
	}
	
	//获取查询总记录数的hql
	public String getQueryCountHql(){
		return "SELECT COUNT(*) " + fromClause + whereClause;
	}
	
	//查询语句hql中?对应的查询条件值集合
	public List<Object> getParameters(){
		return parameters;
	}

}
  